package com.example.armmvvm.ui.customdraw.view

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View
import com.example.arm.ext.dp
import com.example.armmvvm.R

/**
 * 裁剪
 *
 * @author 创建人 ：yanghaozhang
 * @version 1.0
 * @package 包名 ：com.example.armmvvm.ui.custom
 * @createTime 创建时间 ：2021/9/17
 * @modifyBy 修改人 ：
 * @modifyTime 修改时间 ：
 * @modifyMemo 修改备注：
 */
class ClipTestView(context: Context?, attrs: AttributeSet?) : View(context, attrs) {

    private val bitmapWidth = 100.dp

    private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        style = Paint.Style.FILL
    }

    private val clipPath = Path()

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        clipPath.addCircle(width / 2f, height / 2f, bitmapWidth, Path.Direction.CCW)
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            canvas.clipOutPath(clipPath)
        }
        canvas.drawBitmap(
            getAvatar(bitmapWidth.toInt() * 2),
            (width - bitmapWidth * 2) / 2f,
            (height - bitmapWidth * 2) / 2f,
            paint
        )
    }

    private fun getAvatar(width: Int): Bitmap {
        val options = BitmapFactory.Options()
        options.inJustDecodeBounds = true
        BitmapFactory.decodeResource(resources, R.mipmap.icon_avatar, options)
        options.inJustDecodeBounds = false
        options.inDensity = options.outWidth
        options.inTargetDensity = width
        return BitmapFactory.decodeResource(resources, R.mipmap.icon_avatar, options)
    }
}